package cn.nubia.admin.common.utils;


import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * web开发工具类
 *
 * @author yangz
 * @Company : cyou
 * @date 2012-10-10 下午06:05:02
 */
public class WebUtil {
    /**
     * 判断是否是ajax请求
     *
     * @param request
     * @return
     * @author yangz
     * @date 2012-7-30 下午02:59:10
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        return !StringUtils.isEmpty(request.getHeader("X-Requested-With"));
    }

    /**
     * 获取客户端IP地址
     *
     * @param request
     * @return
     */
    public static String getRemoteIP(HttpServletRequest request) {
        String forwardIP = StringUtils.isNotEmpty(request.getHeader("X-FORWARDED-FOR")) ? request.getHeader("X-FORWARDED-FOR") : request.getRemoteAddr();

        if ((StringUtils.isNotEmpty(forwardIP)) && (forwardIP.indexOf(',') != -1)) {
            String[] ipRouters = forwardIP.split(",");
            return ipRouters[0];
        }
        return forwardIP;
    }

    /**
     * 将request的Attribute转化为map
     *
     * @param request
     * @return
     * @author yangz
     * @date 2013-1-23 上午10:09:59
     */
    public static Map<String, Object> toAttributeMap(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        Enumeration<String> enumeration = request.getAttributeNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            result.put(key, request.getAttribute(key));
        }
        return result;
    }
}
